* =======================================================================================================================================================
*
* Code Description: 
* This codefile estimates the predictive power of our fund-level measures of vulnerability (V) and systemicness (S), 
* with regard to a battery of measures of realized fund fragility.
*
* =======================================================================================================================================================
*
* Major output:
* Tables 8, IA.5 and IA.7: Predicting fund-level realized fragility.
* =======================================================================================================================================================
*
* General disclaimer:
* This file directory produces replication code for "Connected Funds". 
* Because we cannot share the underlying data provided by the Bundesbank's Research Data and Service Centre (RDSC) and other subscription data sources, 
* we have included pseudo data to show how the raw data are formatted. 
* Other researchers can go through a similar approval and subscription process to obtain the underlying data. (2023-04-06)
*
*  =======================================================================================================================================================


clear all

global Path "C:\ConnectedFunds_Codebase\"
sysdir set STBPLUS "${Path}Code\Ado"  


* ====================================================================    Preparations    ===============================================================


import delimited "${Path}Data\StresstestModel\Systemicness_ForStata.csv"
save "${Path}Data\StresstestModel\Systemicness_ForStata.dta", replace

clear

use "${Path}Data\JiangEtAl\FullData.dta"

merge 1:1 isin datum using "${Path}Data\FalatoEtAl\FalatoEtAl.dta"
keep if _merge == 3
drop _merge

merge 1:1 isin datum using "${Path}Data\StresstestModel\Systemicness_ForStata.dta"
keep if _merge == 3
drop _merge


* =================================================    Set-up panel and generate and clean x- and y-vars    ====================================================


egen ui_fund = group(isin)
egen ui_date  = group(datum)

sort ui_fund ui_date
xtset ui_fund ui_date

gen log_tna = log(fondsverm * 1000)
gen lag_log_tna = log(L.fondsverm * 1000)
gen log_holdings = log(lag_totalholdings)
gen log_family_tna = log(kag_tna * 1000)

gen tna     = 1000 * fondsverm
gen lag_tna = L.tna

winsor2 returndiv, suffix(W) cuts(1 99) by(artmittel spezial)
winsor2 netflows, suffix(W) cuts(1 99) by(artmittel spezial)

winsor2 leverage, suffix(W) cuts(1 99) by(artmittel spezial)
gen lag_log_leverage = log(l.leverageW)

replace bankg = 1000 * bankg
replace bankg = . if bankg < 0

gen tmp_total 		= bankg + totalholdings_lagp
gen tmp_lag_total 	= L.bankg + lag_totalholdings

gen holdings_lagp_Cash =  bankg
gen lag_holdings_Cash  =  L.bankg

winsor2 systemicness5, suffix(W) cuts(1 99) by(artmittel spezial)
winsor2 systemicness_crossfund5, suffix(W) cuts(1 99) by(artmittel spezial)
winsor2 systemicness_direct5, suffix(W) cuts(1 99) by(artmittel spezial)

winsor2 losscross5, suffix(W) cuts(1 99) by(artmittel spezial)
winsor2 lossdirect5, suffix(W) cuts(1 99) by(artmittel spezial)

rename losscross5W  vulnerability_cross
rename lossdirect5W vulnerability_direct
gen vulnerability = vulnerability_cross + vulnerability_direct

gen systemicness 			= systemicness5W
gen systemicness_crossfund 	= systemicness_crossfund5W
gen systemicness_direct 	= systemicness_direct5W

// Compute trading based fund-level measures of fragility: net trading (volume effect)
xtset ui_fund ui_date
gen pct_total_trading = (totalholdings_lagp - lag_totalholdings) / lag_totalholdings
winsor2 pct_total_trading, suffix(W) cuts(1 99) by(artmittel spezial)
drop pct_total_trading
rename pct_total_tradingW pct_total_trading

// Add simple measure of direct connectedness
capture gen sh_fundholdings = holdings_fund / tna
capture gen sh_heldbyfund   = heldby_fund / tna

winsor2 sh_fundholdings, suffix(W) cuts(1 99) by(artmittel spezial)
winsor2 sh_heldbyfund, suffix(W) cuts(1 99) by(artmittel spezial)

// Generate absolute values
foreach x of varlist netflowsW returndivW systemicness systemicness_crossfund systemicness_direct vulnerability* {
	gen abs_`x' = abs(`x')
}

// Standardize x- and y-vars
foreach x of varlist pct_total_trading netflowsW abs_netflowsW returndivW abs_returndivW abs_systemicness abs_systemicness_crossfund abs_systemicness_direct abs_vulnerability* sh_fundholdingsW sh_heldbyfundW {
	egen norm_`x' = std(`x')
}


* =================================================          Run predictive regression framework          ====================================================


global controls "Lagged_Leverage Lagged_TNA Lagged_DepVar"


* =========================================          Baseline Specification: systemicness and vulnerability          ===========================================

preserve

// y-var: fund return (linear and quantile regression specification)	
forvalues lag = 1/12 {
		
 		sort ui_fund ui_date
		
		gen Lagged_Systemicness 	= l`lag'.norm_abs_systemicness
		gen Lagged_Vulnerability 	= l`lag'.norm_abs_vulnerability
		gen Lagged_FundHoldings		= l`lag'.norm_sh_fundholdingsW
		gen Lagged_HeldbyFunds 		= l`lag'.norm_sh_heldbyfundW
		gen Lagged_Leverage 		= l`lag'.lag_log_leverage
		gen Lagged_TNA 				= l`lag'.lag_log_tna
		gen Lagged_DepVar 			= l`lag'.norm_returndivW 
				
		reghdfe norm_returndivW Lagged_Vulnerability Lagged_Systemicness ${controls}, absorb(ui_fund ui_date) cluster(ui_date ui_fund)		  
		est store nRet_Vul_S_`lag', title("Return(t+`lag')")
		
		xtqreg norm_returndivW Lagged_Vulnerability Lagged_Systemicness ${controls}, quantile(0.25)
		est store qnRet_Vul_S_`lag', title("Return(t+`lag')")
		
		reghdfe norm_returndivW Lagged_FundHoldings Lagged_HeldbyFunds ${controls}, absorb(ui_fund ui_date) cluster(ui_date ui_fund)		  
		est store nRet_SM_`lag', title("Return(t+`lag')")
		
		xtqreg norm_returndivW Lagged_FundHoldings Lagged_HeldbyFunds ${controls}, quantile(0.25)
		est store qnRet_SM_`lag', title("Return(t+`lag')")
		
		drop Lagged_*	
}

// y-var: absolute return
forvalues lag = 1/12 {
	
		sort ui_fund ui_date
		
		gen Lagged_Systemicness 	= l`lag'.norm_abs_systemicness
		gen Lagged_Vulnerability 	= l`lag'.norm_abs_vulnerability
		gen Lagged_FundHoldings		= l`lag'.norm_sh_fundholdingsW
		gen Lagged_HeldbyFunds 		= l`lag'.norm_sh_heldbyfundW
		gen Lagged_Leverage 		= l`lag'.lag_log_leverage
		gen Lagged_TNA 				= l`lag'.lag_log_tna
		gen Lagged_DepVar 			= l`lag'.norm_abs_returndivW
			
		reghdfe norm_abs_returndivW Lagged_Vulnerability Lagged_Systemicness ${controls}, absorb(ui_fund ui_date) cluster(ui_date ui_fund)
		est store nAbsRet_Vul_S_`lag', title("|Return(t+`lag')|")
		
		reghdfe norm_abs_returndivW Lagged_FundHoldings Lagged_HeldbyFunds ${controls}, absorb(ui_fund ui_date) cluster(ui_date ui_fund)		  
		est store nAbsRet_SM_`lag', title("|Return(t+`lag')|")
				
		drop Lagged_*	
}
		

* =========================================          Save regression results in Tables 8, IA.5 and IA.7          ===========================================


// V and S
esttab nRet_Vul_S_*  using "temp.csv", /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(N r2_a, /// 
fmt(%16.0g %9.4g) ///
) noconstant nonotes noomitted mtitles label replace 

clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab8_TabIA5_TabIA7_Predicting fund-level realized fragility.xlsx", sheet("Table 8 - V and S")  sheetmodify   cell(A2)


esttab qnRet_Vul_S_*  using "temp.csv", /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(N r2_a, /// 
fmt(%16.0g %9.4g) ///
) noconstant nonotes noomitted mtitles label replace 

clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab8_TabIA5_TabIA7_Predicting fund-level realized fragility.xlsx", sheet("Table 8 - V and S")  sheetmodify   cell(A22)


esttab nAbsRet_Vul_S_*  using "temp.csv", /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(N r2_a, /// 
fmt(%16.0g %9.4g) ///
) noconstant nonotes noomitted mtitles label replace 

clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab8_TabIA5_TabIA7_Predicting fund-level realized fragility.xlsx", sheet("Table 8 - V and S")  sheetmodify   cell(A42)


// Simple measures instead of S and V
esttab nRet_SM_*  using "temp.csv", /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(N r2_a, /// 
fmt(%16.0g %9.4g) ///
) noconstant nonotes noomitted mtitles label replace 

clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab8_TabIA5_TabIA7_Predicting fund-level realized fragility.xlsx", sheet("Table IA.5 - Simple Measures")  sheetmodify   cell(A2)


esttab qnRet_SM_*  using "temp.csv", /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(N r2_a, /// 
fmt(%16.0g %9.4g) ///
) noconstant nonotes noomitted mtitles label replace 

clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab8_TabIA5_TabIA7_Predicting fund-level realized fragility.xlsx", sheet("Table IA.5 - Simple Measures")  sheetmodify   cell(A22)

esttab nAbsRet_SM_*  using "temp.csv", /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(N r2_a, /// 
fmt(%16.0g %9.4g) ///
) noconstant nonotes noomitted mtitles label replace 

clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab8_TabIA5_TabIA7_Predicting fund-level realized fragility.xlsx", sheet("Table IA.5 - Simple Measures")  sheetmodify   cell(A42)

est clear

restore


* ==================================          Alternatively: decomposed systemicness and decomposed vulnerability          ====================================


preserve

// y-var: fund return (linear and quantile regression specification)	
forvalues lag = 1/12 {
	
 	sort ui_fund ui_date

			
	gen Lagged_Systemicness_Direct 		= l`lag'.norm_abs_systemicness_direct
	gen Lagged_Systemicness_CrossFund 	= l`lag'.norm_abs_systemicness_crossfund
	gen Lagged_Vulnerability 			= l`lag'.norm_abs_vulnerability
	gen Lagged_Vulnerability_Cross 		= l`lag'.norm_abs_vulnerability_cross
	gen Lagged_Vulnerability_Direct 	= l`lag'.norm_abs_vulnerability_direct
	gen Lagged_Leverage 				= l`lag'.lag_log_leverage
	gen Lagged_TNA 						= l`lag'.lag_log_tna
	gen Lagged_DepVar 					= l`lag'.norm_returndivW 
		
	reghdfe norm_returndivW Lagged_Vulnerability_Cross Lagged_Vulnerability_Direct ${controls}, absorb(ui_fund ui_date) cluster(ui_date ui_fund)			
	est store nRet_Decomp_Vul_`lag', title("Return(t+`lag')")
	
	xtqreg norm_returndivW Lagged_Vulnerability_Cross Lagged_Vulnerability_Direct ${controls}, quantile(0.25)
	est store qnRet_Decomp_Vul_`lag', title("Return(t+`lag')")
	
	drop Lagged_*	
}
	
	
// y-var: absolute return	
forvalues lag = 1/12 {
	
 	sort ui_fund ui_date
		
	gen Lagged_Systemicness_Direct 		= l`lag'.norm_abs_systemicness_direct
	gen Lagged_Systemicness_CrossFund 	= l`lag'.norm_abs_systemicness_crossfund
	gen Lagged_Vulnerability 			= l`lag'.norm_abs_vulnerability
	gen Lagged_Vulnerability_Cross 		= l`lag'.norm_abs_vulnerability_cross
	gen Lagged_Vulnerability_Direct 	= l`lag'.norm_abs_vulnerability_direct
	gen Lagged_Leverage 				= l`lag'.lag_log_leverage
	gen Lagged_TNA 						= l`lag'.lag_log_tna
	gen Lagged_DepVar 					= l`lag'.norm_abs_returndivW 
	
	reghdfe norm_abs_returndivW Lagged_Vulnerability_Cross Lagged_Vulnerability_Direct ${controls}, absorb(ui_fund ui_date) cluster(ui_date ui_fund)			
	est store nAbsRet_Decomp_Vul_`lag', title("|Return(t+`lag')|")
		
	drop Lagged_*	
}


// yvar: net trading behaviour
forvalues lag = 1/12 {
	
 	sort ui_fund ui_date
			
	gen Lagged_Systemicness_Direct 		= l`lag'.norm_abs_systemicness_direct
	gen Lagged_Systemicness_CrossFund 	= l`lag'.norm_abs_systemicness_crossfund
	gen Lagged_Vulnerability 			= l`lag'.norm_abs_vulnerability
	gen Lagged_Systemicness 			= l`lag'.norm_abs_systemicness
	gen Lagged_Vulnerability_Cross 		= l`lag'.norm_abs_vulnerability_cross
	gen Lagged_Vulnerability_Direct 	= l`lag'.norm_abs_vulnerability_direct
	gen Lagged_FundHoldings				= l`lag'.norm_sh_fundholdingsW
	gen Lagged_HeldbyFunds 				= l`lag'.norm_sh_heldbyfundW
	gen Lagged_Leverage 				= l`lag'.lag_log_leverage
	gen Lagged_TNA 						= l`lag'.lag_log_tna
	gen Lagged_DepVar 					= l`lag'.norm_pct_total_trading 


	reghdfe norm_pct_total_trading Lagged_Vulnerability Lagged_Systemicness ${controls}, absorb(ui_fund ui_date) cluster(ui_date ui_fund)			
	est store nTrad_Vul_S_`lag', title("Net Trading(t+`lag')")
	
	reghdfe norm_pct_total_trading Lagged_Vulnerability_Cross Lagged_Vulnerability_Direct ${controls}, absorb(ui_fund ui_date) cluster(ui_date ui_fund)			
	est store nTrad_Decomp_Vul_`lag', title("Net Trading (t+`lag')")
		
	reghdfe norm_pct_total_trading Lagged_FundHoldings Lagged_HeldbyFunds ${controls}, absorb(ui_fund ui_date) cluster(ui_date ui_fund)			
	est store nTrad_SM_`lag', title("Net Trading(t+`lag')")	
	
	drop Lagged_*	
}
			

* ======================================          Save regression results in Tables 8, IA.5 and IA.7          =========================================			
			

* V decomposed *
esttab nRet_Decomp_Vul_*  using "temp.csv", /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(N r2_a, /// 
fmt(%16.0g %9.4g) ///
) noconstant nonotes noomitted mtitles label replace 

clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab8_TabIA5_TabIA7_Predicting fund-level realized fragility.xlsx", sheet("Table IA.7 - V decomposed")  sheetmodify   cell(A2)


esttab nAbsRet_Decomp_Vul_*  using "temp.csv", /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(N r2_a, /// 
fmt(%16.0g %9.4g) ///
) noconstant nonotes noomitted mtitles label replace 

clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab8_TabIA5_TabIA7_Predicting fund-level realized fragility.xlsx", sheet("Table IA.7 - V decomposed")  sheetmodify   cell(A42)


esttab qnRet_Decomp_Vul_*  using "temp.csv", /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(N r2_a, /// 
fmt(%16.0g %9.4g) ///
) noconstant nonotes noomitted mtitles label replace 

clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab8_TabIA5_TabIA7_Predicting fund-level realized fragility.xlsx", sheet("Table IA.7 - V decomposed")  sheetmodify   cell(A22)


* Trading behaviour *
esttab nTrad_Vul_S_*  using "temp.csv", /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(N r2_a, /// 
fmt(%16.0g %9.4g) ///
) noconstant nonotes noomitted mtitles label replace 

clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab8_TabIA5_TabIA7_Predicting fund-level realized fragility.xlsx", sheet("Table 8 - V and S")  sheetmodify   cell(A62)


esttab nTrad_Decomp_Vul_*  using "temp.csv", /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(N r2_a, /// 
fmt(%16.0g %9.4g) ///
) noconstant nonotes noomitted mtitles label replace 

clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab8_TabIA5_TabIA7_Predicting fund-level realized fragility.xlsx", sheet("Table IA.7 - V decomposed")  sheetmodify   cell(A62)


esttab nTrad_SM_*  using "temp.csv", /// 
b(3) t(3) star(* 0.10 ** 0.05 *** 0.01) /// 
stats(N r2_a, /// 
fmt(%16.0g %9.4g) ///
) noconstant nonotes noomitted mtitles label replace 

clear
insheet using temp.csv
export excel using "${Path}Paper\Tables\Tab8_TabIA5_TabIA7_Predicting fund-level realized fragility.xlsx", sheet("Table IA.5 - Simple Measures")  sheetmodify   cell(A62)

est clear

restore